import React, {useEffect, useRef, useState} from "react";
import {
  Button,
  Card,
  Carousel,
  Col,
  Form,
  Input, message,
  Modal,
  Popconfirm,
  Row,
  Select, Space,
  Switch,
  Table,
  Tree,
  TreeSelect
} from "antd";
import {PageContainer} from "@ant-design/pro-layout";
import {ModalForm, ProFormSelect, ProFormText} from "@ant-design/pro-form";
import './index.less'
import {ColumnsType} from "antd/es/table";
import {ProFormItem} from "@ant-design/pro-components";
import {getLinkTypeList} from "@/services/linkManager";
import {ActionType} from "@ant-design/pro-table";
import ProTable from '@ant-design/pro-table';
import {
  CopyFilled,
  DeleteOutlined,
  DownOutlined,
  EditOutlined,
  PlusCircleOutlined,
  UpOutlined,
} from "@ant-design/icons";
import {getMenuList, updateMenuList, updateUpAndDown} from "@/services/menuSetting";
import {getCategoryList} from "@/services/category";
import {addSubSystem, updateSubSystem} from "@/services/subSysFun";
import preview from "@/assets/images/preview.png";
import {HOMEPAGE_URL} from "../../../../proxyConfig";

const Index: React.FC = () =>{
  const [form] = Form.useForm();

  const [menus,setMenus] = useState([])
  const [treeData, setTreeData] = useState([]);

  interface DataType {
    key: React.Key;
    name: string;
    age: number;
    address: string;
    description: string;
  }
  const getMenus = async() =>{
    const res = await getMenuList()
    res.data.map(i=>{
      console.log(i);
      i.cataListInfo.map(j=>{
        j.parentNumId = i.id
      })
    })
    console.log(res.data);
    setMenus(res.data)
  }
  useEffect(()=>{
    getMenus()
    getCategory()
  },[])
  const [currentRecord,setRecord] = useState({})
  const [addShow,setAddShow] = useState(false)
  const [editShow,setEditShow] = useState(false)
  const formLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 } };
  const [loadingTable, setLoadingTable] = useState(false);

  const addMenu = (e)=>{
    console.log(e);
  }
  const moveAction = async(record,direction,type)=>{
    const params = {upOrDown:direction,type,id:type==1?record.id:record.parentNumId||'',cataInfo:type==1?'':record.id}
    console.log(params);
    const res = await updateUpAndDown(params)
    if(res.code==0){
      message.success('操作成功');
      getMenus()
    }
  }
  const columns: ColumnsType<DataType> = [
    { title: '栏目名称', dataIndex: 'menuName', key: 'menuName' },
    {
      title: '操作',
      dataIndex: '',
      key: '+',
      render: (value,record,index) =>
        <Space>
          <a onClick={() => {
            setRecord(record);
            setAddShow(true)
          }}>
            <Button shape={'round'} icon={<PlusCircleOutlined/>} type={'primary'}>
              新增
            </Button>
          </a>
          <a onClick={() => {
            setRecord(record);
            setEditShow(true)
          }}>
            <Button shape={'round'} icon={<EditOutlined/>}>
              修改
            </Button>
          </a>
          <a onClick={() => moveAction(record, 'up', 1)}>
            <Button shape={'round'} icon={<UpOutlined/>}>
              上移
            </Button>
          </a>
          <a onClick={() => moveAction(record, 'down', 1)}>
            <Button shape={'round'} icon={<DownOutlined/>}>
              下移
            </Button>
          </a>
        </Space>
    },
  ];
  const delMenu = async (e, f) => {
    console.log(e, f);
    const cataList = f.cataList.split(',')
    const index = cataList.findIndex(i => i == e.id)
    cataList.splice(index, 1)
    const params = {id:f.id,menuName:f.menuName,cataList:cataList.join(',')}
    const res = await updateMenuList(params)
    if(res){
      message.success('删除成功')
      getMenus()
    }else{
      message.success('删除失败')
    }
  }
  //更改树结构
  const changeTreeData = (data) => {
    for (let i = 0; i < data.length; i++) {
      const element = data[i];
      element.value = element.id;
      element.title = element.name;
      if (element.children && element.children.length > 0) {
        changeTreeData(element.children);
      }
    }
    return data;
  };
  //查询分类
  const getCategory = () => {
    //获取组list
    getCategoryList({type:'topic'}).then(async (res) => {
      const data = changeTreeData(res.data);
      setTreeData(data);
    });
  };

  const actionRef = useRef<ActionType>();

  const data: DataType[] = [
    {
      level: '一级栏目',
      name: '警务要闻',
      'cateList':[
        {
          level: '二级栏目',
          name: '高层声音',
        }
      ]
    },

  ];
  useEffect(()=>{
    console.log(menus,'menus');
  },[menus])
  /*const getMenuDiv = ()=>{
    return (
      <div className={'menuBox'}>
        {
          menus.map((i,index)=>{
            return (
              <div className={'menuItemBox'}>
                <div key={index} className={'menuItem'}>{i.name}
                </div>
                <div className={'childMenuBox'}>
                  {
                    i.cate_list.map((j,index1)=>{
                      return(
                        <div key={index1} className={'childMenu'}>{j.name}</div>
                      )
                    })
                  }
                </div>

              </div>

            )
          })
        }
      </div>
    )
  }*/
  const getChildrenTable = (source,fatherMenu)=>{
    const myColumns: ColumnsType<DataType> = [
      { title: '栏目名称', dataIndex: 'name', key: 'name' },
      {
        title: '操作',
        dataIndex: '',
        key: 'x',
        render: (val,record) => {
          return (
            <Space>
              <div>
                <Popconfirm title="确定是否删除?" onConfirm={() => delMenu(record, fatherMenu)} key="delete">
                  <a style={{color: 'red'}}>
                    <Button danger className={'buttonMargin'} shape={'round'} icon={<DeleteOutlined/>}>
                      删除
                    </Button>
                  </a>
                </Popconfirm>
              </div>

              <a onClick={() => moveAction(record, 'up', 2)}>
                <Button shape={'round'} icon={<UpOutlined/>}>
                  上移
                </Button>
              </a>
              <a onClick={() => moveAction(record, 'down', 2)}>
                <Button shape={'round'} icon={<DownOutlined/>}>
                  下移
                </Button>
              </a>
              <a onClick={() => moveAction(record, 'down', 2)}>
                <Button shape={'round'} icon={<CopyFilled/>}>
                  复制链接
                </Button>
              </a>
            </Space>
          )
        },
      },
    ];

    return (
      <div style={{padding: '10px 30px'}}>
        <Table
          columns={myColumns}
          rowKey={'name'}
          expandable={{
            rowExpandable: (record) => false,
          }}
          dataSource={source}
        />
      </div>

    )
  }
  return (
    <PageContainer
      header={{
        title: false,
      }}
    >
      <Card
        title="菜单设置"
        extra={
          <>
          </>
        }
      >
        <ProTable
          className={'myProTable'}
          tableStyle={{ textAlign: 'center' }}
          options={false}
          loading={loadingTable}
          actionRef={actionRef}
          columns={columns}
          rowKey={'menuName'}
          expandable={{
            expandedRowRender: (record) => <p style={{ margin: 0 }}>{getChildrenTable(record.cataListInfo,record)}</p>,
            rowExpandable: (record) => record.cataListInfo,
          }}
          dataSource={menus}
        />

        <ModalForm
          title="修改名称"
          form={form}
          width="600px"
          modalProps={{destroyOnClose:true}}
          layout={'horizontal'}
          {...formLayout}
          onVisibleChange={bool=>{
            setEditShow(bool)
            if(!bool) {
              setEditShow(false)
            }
          }}
          visible={editShow}
          onFinish={async (value) => {
            console.log(value,'values');
            const params = {id:currentRecord.id,
              menuName:value.name,
            }
            const res = await updateMenuList(params)
            if(res){
              message.success('修改成功')
              setEditShow(false)
              getMenus()
            }else{
              message.success('修改失败')
            }
          }}
        >
          <ProFormText
            rules={[
              {
                required: true,
                message: '栏目名称必填！',
              },
            ]}
            width="md"
            name="name"
            placeholder="请输入栏目名称"
            label="栏目名称"
          />
        </ModalForm>

        <ModalForm
          title="添加栏目"
          form={form}
          width="600px"
          modalProps={{destroyOnClose:true}}

          layout={'horizontal'}
          {...formLayout}
          onVisibleChange={bool=>{
            setAddShow(bool)
            if(!bool) {
              setAddShow(false)
            }
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }}
          visible={addShow}
          onFinish={async (value) => {
            const params = {id:currentRecord.id,
              menuName:currentRecord.menuName,
              cataList:currentRecord.cataList+','+value.linkTypeId}
            const res = await updateMenuList(params)
            if(res){
              message.success('添加成功')
              setAddShow(false)
              getMenus()
            }else{
              message.success('添加失败')
            }
          }}
        >
          <ProFormItem
            rules={[
              {
                required: true,
                message: '请选择栏目!',
              },
            ]}
            width="md"
            label="添加栏目"
            // width="60%"
            name="linkTypeId"
            placeholder="请选择"
          >
            <TreeSelect treeData={treeData} />
          </ProFormItem>
        </ModalForm>
      </Card>
    </PageContainer>
  )
}
export default Index;
